const ASSEMBLER = Symbol("ASSEMBLER");
class Storage {
  constructor(prefix, storage = sessionStorage) {
    this.$prefix = prefix;
    this.$storage = storage;
  }

  [ASSEMBLER](key) {
    return this.$prefix + "::" + key;
  }

  write(key, value, expireSeconds = 9999999999) {
    let expireAt = new Date();
    expireAt.setSeconds(expireAt.getSeconds() + expireSeconds);
    let data = {
      key: key,
      value: value,
      expire: expireAt
    };
    this.$storage.setItem(this[ASSEMBLER](key), JSON.stringify(data));
  }
  read(key) {
    let dataKey = this[ASSEMBLER](key);
    let dataString = this.$storage.getItem(dataKey);
    if (!dataString) {
      return;
    }
    try {
      let data = JSON.parse(dataString);
      if (new Date() > data.expireAt) {
        return;
      }
      return data.value;
    } catch (e) {
      console.log("数据格式不正确", dataString, e);
      this.$storage.removeItem(dataKey);
    }
  }
}

const DEFAULT_STORAGE = new Storage("ANYWHERE");
export const writeStorage = (...args) => DEFAULT_STORAGE.write(...args);
export const readStorage = (...args) => DEFAULT_STORAGE.read(...args);

export default {
  write(key, value, expireSeconds) {
    DEFAULT_STORAGE.write(key, value, expireSeconds);
  },
  read(key) {
    return DEFAULT_STORAGE.read(key);
  },
  install(Vue) {
    Vue.prototype.$storage = this;
    Vue.prototype.writeStorage = writeStorage;
    Vue.prototype.readStorage = readStorage;
  }
};

export { Storage };
